package com.baiku.sanhos.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * jwt工具类
 */
@Slf4j
@Data
@Component
public class JWTEasyUtil {

    // 密钥
    @Value("${Bai-San.token.SECRET}")
    private String SECRET;
    @Value("${Bai-San.token.duration}")
    private long durationInMinute;

    // 创建token
    // 传入userid
    public String createToken(String userId) {
        Date date = new Date(System.currentTimeMillis() + 1L * 60 * 1000 * durationInMinute);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId)
                .setIssuedAt(new Date())
                .setExpiration(date)
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    // 校验jwt
    public Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("jwt match error: {}", e);
            return null;
        }
    }

    // 校验token是否有效
    public boolean validateToken(String token) {
        Claims claims = parseToken(token);
        return claims != null && !claims.isEmpty();
    }
}
